package bas.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import bas.system.Util;

public class FileIO
{
    private static BufferedReader mReader;
    private static BufferedWriter mWriter;
    static File file;
    
    public static boolean joinMember(String id, String pw, String name, String regId, String addr)
    {
    	boolean isCreated = false;
        mWriter = null;
        File f = new File(Util.getMemberDirPath());

        if (!f.exists())
        {
            f.mkdir();
        }

        try
        {
            mWriter = new BufferedWriter(new FileWriter(new File(f, id + ".txt")));
            StringBuffer sb = new StringBuffer();
            sb.append(id);
            sb.append("//");
            sb.append(pw);
            sb.append("//");
            sb.append(name);
            sb.append("//");
            sb.append(regId);
            sb.append("//");
            sb.append(addr);
            mWriter.write(sb.toString());
            mWriter.newLine();
            mWriter.write("000000");
            mWriter.newLine();
            mWriter.write("0");
            mWriter.close();
        }
        catch (IOException e)
        {
            System.out.println("Writing Error");
            isCreated = false;
        }

        if(new File(f, id + ".txt").exists())
        {
        	isCreated = true;
        }

        return isCreated;
    }

    public static boolean saveRequestList(String id, boolean isCreation)
    {
    	boolean isSaved = false;
        mWriter = null;
        File f = null;
        String fileName = null;

        if (isCreation)
        {
            f = new File(Util.getCreationDirPath());
            fileName = Util.getCreationFileName();
        }
        else
        {
            f = new File(Util.getDeletionDirPath());
            fileName = Util.getDeletionFileName();
        }

        if (!f.exists())
        {
            f.mkdir();
        }

        try
        {
            mWriter = new BufferedWriter(new FileWriter(new File(f, fileName), true));
            mWriter.write(id);
            mWriter.write("//");
            mWriter.close();
            
            isSaved = true;
        }
        catch (IOException e)
        {
            System.out.println("Writing Error");
            isSaved = false;
        }
        
        return isSaved;
    }

    public static ArrayList<String> get(String id) 
    {
        mReader = null;
        ArrayList<String> infoList = new ArrayList<String>();
        int lineNum = 1;

        try
        {
            mReader = new BufferedReader(new FileReader(new File(Util.getMemberDirPath(), id + ".txt")));
            String str;
            while((str = mReader.readLine()) != null)
            {
                if(lineNum == 1)
                {
                    String[] splitText = str.split("//");
                    for(int i = 0; i < 5; i++)
                    {
                        infoList.add(splitText[i]);
                    }
                }
                else if(lineNum == 2)
                {
                    infoList.add(str);
                }
                else if(lineNum == 3)
                {
                    infoList.add(str);
                }
                lineNum++;
            }
            mReader.close();
        }
        catch (IOException e)
        {
            ;
        }
        return infoList;
    }

    public static String getPw(String id)
    {
        mReader = null;
        String pw = null;
        File f = null;

        if (id.equals("admin"))
        {
            f = new File(Util.getAdminDirPath(), "admin.txt");
        } 
        else
        {
        	f = new File(Util.getMemberDirPath(), id + ".txt");
        }

        try
        {
            mReader = new BufferedReader(new FileReader(f));
            String str = null;

            str = mReader.readLine();
            String[] splitText = str.split("//");
            pw = splitText[1];
            mReader.close();
        }
        catch (IOException e)
        {
            ;
        }
        return pw;
    }

    public static boolean checkRegNum(String regNum)
    {
        boolean isDuplicatedRegNum = false;
        mReader = null;
        File path = new File(Util.getMemberDirPath());
        File[] fileList = path.listFiles();

        for(int i = 0; i < fileList.length; i++)
        {
            try {
                mReader = new BufferedReader(new FileReader(fileList[i]));
                String str = mReader.readLine();
                String[] splitText = str.split("//");
                String existRegNum = splitText[3];

                if(existRegNum.equals(regNum))
                {
                    isDuplicatedRegNum = true;
                }
                mReader.close();
            }
            catch(IOException e)
            {
                ;
            }
        }
        return isDuplicatedRegNum;
    }

    public static void setLatestAccNum(int accNum)
    {
        mWriter = null;
        File f = new File(Util.getAdminDirPath());

        if (!f.exists())
        {
            f.mkdir();
        }

        try
        {
            mWriter = new BufferedWriter(new FileWriter(new File(f, "latest.txt")));
            mWriter.write(Integer.toString(accNum));
            mWriter.close();
        }
        catch (IOException e)
        {
            ;
        }
    }

    private static int getLatestAccNum()
    {
        mReader = null;
        String accNum = null;

        try
        {
            mReader = new BufferedReader(new FileReader(new File(
                    Util.getAdminDirPath(), "latest.txt")));
            String str = null;

            while ((str = mReader.readLine()) != null)
            {
                accNum = str;
            }
            mReader.close();
        }
        catch (IOException e)
        {
            ;
        }
        return Integer.parseInt(accNum);
    }

    public static boolean setAccNum(String id)
    {
        boolean isSet = false;
        mReader = null;
        File inFile = new File(Util.getMemberDirPath(), id + ".txt");
        File tempFile = new File(Util.getMemberDirPath(), "temp.txt");

        PrintWriter writer = null;
        String thisLine = null;

        int accNum = getLatestAccNum();
        accNum += 1;
        int lineNum = 1;

        try
        {
            mReader = new BufferedReader(new FileReader(inFile));
            writer = new PrintWriter(new FileOutputStream(tempFile));
            while((thisLine = mReader.readLine()) != null)
            {
                if(lineNum == 2)
                {
                    writer.println(Integer.toString(accNum));
                }
                else
                {
                    writer.println(thisLine);
                }
                lineNum++;
            }

            writer.flush();
            writer.close();
            mReader.close();

            mReader = new BufferedReader(new FileReader(tempFile));
            writer = new PrintWriter(new FileOutputStream(inFile));
            while((thisLine = mReader.readLine()) != null)
            {
                writer.println(thisLine);
            }

            writer.flush();
            writer.close();
            mReader.close();
            tempFile.delete();
            
            isSet = true;
        }
        catch (IOException e)
        {
            isSet = false;
        }
        setLatestAccNum(accNum);

        return isSet;
    }

    public static void setBalance(String id, int balance)
    {
        mReader = null;
        File inFile = new File(Util.getMemberDirPath(), id + ".txt");
        File tempFile = new File(Util.getMemberDirPath(), "temp.txt");

        PrintWriter writer = null;
        String thisLine = null;

        int lineNum = 1;

        try
        {
            mReader = new BufferedReader(new FileReader(inFile));
            writer = new PrintWriter(new FileOutputStream(tempFile));
            while((thisLine = mReader.readLine()) != null)
            {
                if(lineNum == 3)
                {
                    writer.println(Integer.toString(balance));
                }
                else
                {
                    writer.println(thisLine);
                }
                lineNum++;
            }
            writer.flush();
            writer.close();
            mReader.close();

            mReader = new BufferedReader(new FileReader(tempFile));
            writer = new PrintWriter(new FileOutputStream(inFile));
            while((thisLine = mReader.readLine()) != null)
            {
                writer.println(thisLine);
            }

            writer.flush();
            writer.close();
            mReader.close();
            tempFile.delete();
        }
        catch (IOException e)
        {
            ;
        }
    }

    public static int getBalance(String id)
    {
        mReader = null;
        int balance = 0;
        int lineNum = 1;
        File f = new File(Util.getMemberDirPath(), id + ".txt");

        try
        {
            mReader = new BufferedReader(new FileReader(f));
            String str = null;

            while ((str = mReader.readLine()) != null)
            {
                if(lineNum == 3)
                {
                    balance = Integer.parseInt(str);
                }
            }
            mReader.close();
        }
        catch (IOException e)
        {
            ;
        }
        return balance;
    }

    public static String findAccount(String accNum)
    {
        mReader = null;
        File path = new File(Util.getMemberDirPath());
        File[] fileList = path.listFiles();
        int lineNum;
        String[] splitText = null;
        String accountId = null;

        for(int i = 0; i < fileList.length; i++)
        {
            try {
                mReader = new BufferedReader(new FileReader(fileList[i]));
                String str;
                lineNum = 1;
                while((str = mReader.readLine()) != null)
                {
                    if(lineNum == 1)
                    {
                        splitText = str.split("//");
                    }
                    else if(lineNum == 2)
                    {
                        if(accNum.equals(str))
                        {
                            accountId = splitText[0];
                        }
                    }
                    lineNum++;
                }
                mReader.close();
            }
            catch(IOException e)
            {
                ;
            }
        }

        return accountId;
    }

    public static void deleteAcc(String accNum)
    {
    	String id = findAccount(accNum);
        System.gc();
 
        file = new File(Util.getMemberDirPath(), id + ".txt");
        try {
			mReader = new BufferedReader(new FileReader(file));
			mReader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	    if(file.exists())
		{ 
		    file.delete();
		    deleteComplete(id);
		}
		
    }

    private static void deleteComplete(String id)
    {
        mReader = null;
        
        PrintWriter writer = null;

        File source = new File(Util.getCreationDirPath(), "Complete.txt");
        File target = new File(Util.getCreationDirPath(), "temp.txt");

        try
        {
            mReader = new BufferedReader(new FileReader(source));
            writer = new PrintWriter(new FileOutputStream(target));

            String[] splitText;
            String str = mReader.readLine();
            splitText = str.split("//");

            for(int i = 0; i < splitText.length; i++)
            {
                if(!id.equals(splitText[i]))
                {
                    writer.write(splitText[i] + "//");
                }
            }

            writer.flush();
            writer.close();
            mReader.close();

            mReader = new BufferedReader(new FileReader(target));
            writer = new PrintWriter(new FileOutputStream(source));
            str = mReader.readLine();
            if(str == null)
            {
                str = "";
            }
            writer.print(str);

            writer.flush();
            writer.close();
            mReader.close();
            target.delete();

            writer = new PrintWriter(new FileOutputStream(new File(Util.getDeletionDirPath(), Util.getDeletionFileName())));
            writer.print("");
            writer.close();
        }
        catch(IOException e)
        {
        	e.printStackTrace();
        }
    }

    public static String[] getRequestList(boolean isCreation)
    {
        mReader = null;
        String[] list = null;
        File f = null;

        if (isCreation)
        {
            f = new File(Util.getCreationDirPath(), Util.getCreationFileName());
        }
        else
        {
        	f = new File(Util.getDeletionDirPath(), Util.getDeletionFileName());
        }

        try
        {
            mReader = new BufferedReader(new FileReader(f));
            String str = null;

            while ((str = mReader.readLine()) != null)
            {
                list = str.split("//");
            }
            mReader.close();
        }
        catch (IOException e)
        {
            ;
        }
        return list;
    }

    public static void requestComplete()
    {
        mReader = null;
        mWriter = null;
        PrintWriter writer = null;
        File f = new File(Util.getCreationDirPath(), Util.getCreationFileName());

        File tempFile = new File(Util.getCreationDirPath(), "Complete.txt");

        try
        {
        	mReader = new BufferedReader(new FileReader(f));
        	mWriter = new BufferedWriter(new FileWriter(tempFile, true));
            writer = new PrintWriter(mWriter, true);

            String idList = mReader.readLine();
            writer.print(idList);

            writer.flush();
            writer.close();
            mReader.close();

            writer = new PrintWriter(new FileOutputStream(f));
            writer.print("");
            writer.close();
        }
        catch(IOException e)
        {
            ;
        }
    }

    public static boolean changeAdminPw(String newPw)
    {
        boolean isChanged = false;
        File source = new File(Util.getAdminDirPath(), "admin.txt");
        File target = new File(Util.getAdminDirPath(), "temp.txt");
        mReader = null;
        PrintWriter writer = null;
        
        try
        {
            mReader = new BufferedReader(new FileReader(source));
            writer = new PrintWriter(new FileOutputStream(target));

            String[] splitText;
            String str = mReader.readLine();
            splitText = str.split("//");

            writer.write(splitText[0] + "//" + newPw);

            writer.flush();
            writer.close();
            mReader.close();

            mReader = new BufferedReader(new FileReader(target));
            writer = new PrintWriter(new FileOutputStream(source));
            str = mReader.readLine();
            writer.write(str);

            writer.flush();
            writer.close();
            mReader.close();
            target.delete();

            isChanged = true;
        }
        catch(IOException e)
        {
            ;
        }

        return isChanged;
    }

    public static void setPassword(String id, String password)
    {
        mReader = null;
        mWriter = null;

        File source =new File(Util.getMemberDirPath(), id + ".txt");
        File target = new File(Util.getMemberDirPath(), "temp.txt");
        int lineNum = 1;

        try
        {
            mReader = new BufferedReader(new FileReader(source));
            mWriter = new BufferedWriter(new FileWriter(target));

            String[] splitText;
            String str;
            while((str = mReader.readLine()) != null)
            {
                if(lineNum == 1)
                {
                    splitText = str.split("//");

                    StringBuffer sb = new StringBuffer();
                    sb.append(splitText[0]);
                    sb.append("//");
                    sb.append(password);
                    sb.append("//");
                    sb.append(splitText[2]);
                    sb.append("//");
                    sb.append(splitText[3]);
                    sb.append("//");
                    sb.append(splitText[4]);
                    mWriter.write(sb.toString());
                }
                else if(lineNum == 2)
                {
                	mWriter.write(str);
                }
                else if(lineNum == 3)
                {
                	mWriter.write(str);
                }
                mWriter.newLine();
                lineNum++;
            }

            mWriter.flush();
            mWriter.close();
            mReader.close();

            mReader = new BufferedReader(new FileReader(target));
            mWriter = new BufferedWriter(new FileWriter(source));
            while((str = mReader.readLine()) != null)
            {
            	mWriter.write(str);
            	mWriter.newLine();
            }

            mWriter.flush();
            mWriter.close();
            mReader.close();
            target.delete();
        }
        catch(IOException e)
        {
            ;
        }
    }
    
    public static void setAddress(String id, String address)
    {
        mReader = null;
        mWriter = null;

        File source =new File(Util.getMemberDirPath(), id + ".txt");
        File target = new File(Util.getMemberDirPath(), "temp.txt");
        int lineNum = 1;

        try
        {
            mReader = new BufferedReader(new FileReader(source));
            mWriter = new BufferedWriter(new FileWriter(target));

            String[] splitText;
            String str;
            while((str = mReader.readLine()) != null)
            {
                if(lineNum == 1)
                {
                    splitText = str.split("//");

                    StringBuffer sb = new StringBuffer();
                    sb.append(splitText[0]);
                    sb.append("//");
                    sb.append(splitText[1]);
                    sb.append("//");
                    sb.append(splitText[2]);
                    sb.append("//");
                    sb.append(splitText[3]);
                    sb.append("//");
                    sb.append(address);
                    mWriter.write(sb.toString());
                }
                else if(lineNum == 2)
                {
                    mWriter.write(str);
                }
                else if(lineNum == 3)
                {
                	mWriter.write(str);
                }
                mWriter.newLine();
                lineNum++;
            }

            mWriter.flush();
            mWriter.close();
            mReader.close();

            mReader = new BufferedReader(new FileReader(target));
            mWriter = new BufferedWriter(new FileWriter(source));
            while((str = mReader.readLine()) != null)
            {
            	mWriter.write(str);
            	mWriter.newLine();
            }

            mWriter.flush();
            mWriter.close();
            mReader.close();
            target.delete();
        }
        catch(IOException e)
        {
            ;
        }
    }
    
    public static String[] getCompletedList(){
    	
    	 mReader = null;
         String[] list = null;
         File f = new File(Util.getCreationDirPath(), Util.getCompleteFileName());

         try
         {
             mReader = new BufferedReader(new FileReader(f));
             String str = null;

             while ((str = mReader.readLine()) != null)
             {
                 list = str.split("//");
             }
             mReader.close();
         }
         catch (IOException e)
         {
             ;
         }
         
         return list;
    }
}
